#include "stepper_controller.h"

hw_timer_t *timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

static volatile uint8_t busy = false;

void IRAM_ATTR timer_callback()
{
    TIMERG0.int_clr_timers.t0 = 1;
    if (busy)
    {
        return; // The busy-flag is used to avoid reentering this interrupt
    }
    // 临界段
    
    //portENTER_CRITICAL_ISR(&timerMux);
    if (reinterpret_cast<StepperControllerClass *>(&StepCtrl)->callBackFun != NULL)
        reinterpret_cast<StepperControllerClass *>(&StepCtrl)->callBackFun();
    //portEXIT_CRITICAL_ISR(&timerMux);
    TIMERG0.hw_timer[0].config.alarm_en = TIMER_ALARM_EN;
    busy = false;
}

StepperControllerClass::StepperControllerClass()
{
}
StepperControllerClass::~StepperControllerClass()
{
    end();
}

bool StepperControllerClass::begin(void (*_callBackFun)(void))
{
    // 定时器
    timer = timerBegin(0 /*定时器0*/, 80 /*分频系数80M/80=1M*/, true /*向上计数*/);
    timerAttachInterrupt(timer, &timer_callback /*回调函数*/, true /*边沿触发*/);
    timerAlarmWrite(timer, 200 /*触发阈值1M/50=20k*/, true /*自动重载*/);
    timerAlarmEnable(timer);

    // 注册回调函数
    callBackFun = _callBackFun;

    return true;
}

bool StepperControllerClass::end()
{
    timerAlarmDisable(timer);
    return true;
}

StepperControllerClass StepCtrl;